# Generation of example options on the controller.
AutoRest.ar_require_relative __FILE__, 'configuration_generator.rb'

class ArSpecScaffoldGenerator < Rails::Generator::NamedBase
  default_options :skip_migration => false
  
  attr_reader   :controller_name,
                :controller_class_path,
                :controller_file_path,
                :controller_class_nesting,
                :controller_class_nesting_depth,
                :controller_class_name,
                :controller_singular_name,
                :controller_plural_name,
                :resource_edit_path,
                :default_file_extension
  alias_method  :controller_file_name,  :controller_singular_name
  alias_method  :controller_table_name, :controller_plural_name

  def initialize(runtime_args, runtime_options = {})
    super

    @controller_name = @name.pluralize

    base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
    @controller_class_name_without_nesting, @controller_singular_name, @controller_plural_name = inflect_names(base_name)

    if @controller_class_nesting.empty?
      @controller_class_name = @controller_class_name_without_nesting
    else
      @controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
    end
    
    if ActionView::Base.const_defined?('DEFAULT_TEMPLATE_HANDLER_PREFERENCE') &&
       ActionView::Base::DEFAULT_TEMPLATE_HANDLER_PREFERENCE.include?(:erb)
      @default_file_extension = "html.erb"
    else
      @default_file_extension = "rhtml"
    end
    
    @resource_edit_path = RAILS_GEM_VERSION > "1.2.3" ? "/edit" : ";edit"
  end

  def manifest
    record do |m|
      
      # Check for class naming collisions.
      m.class_collisions(controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper")
      m.class_collisions(class_path, "#{class_name}")

      # Controller, helper, views directories.
      m.directory(File.join('app/models', class_path))
      m.directory(File.join('app/controllers', controller_class_path))
      m.directory(File.join('app/helpers', controller_class_path))
      m.directory(File.join('app/views', controller_class_path, controller_file_name))
      
      # Directory for default actions
      m.directory('lib/auto_rest/default_methods')
      
      # Copy labels class file
      m.template('labels.rb', 'lib/auto_rest/labels.rb')
      
      # Copy the files
      for file in defaul_methods_files 
        m.file(file, File.join('lib/auto_rest/default_methods', File.basename(file)))
      end
      
      m.directory(File.join('app/views', 'auto_rest_shared'))
      
      for file in views_files
        destination= File.join 'app/views', 'auto_rest_shared', "#{file}.#{default_file_extension}"
        m.file("#{file}.rhtml", destination)
      end
      
      m.template('controller.rb',
        File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb")
      )
      m.template('helper.rb',
        File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb")
      )
      m.template('model.rb',
        File.join('app/models', class_path, "#{file_name}.rb")
      )
      
      # Progress indicator
      m.template('progress4.gif', 'public/images/progress4.gif')
      
      # SPEC SCAFFOLDING -------------------------------------------------------
      unless options[:skip_rspecing]
        m.directory(File.join('spec/controllers', controller_class_path))
        m.directory(File.join('spec/models', class_path))
        m.directory(File.join('spec/helpers', class_path))
        m.directory File.join('spec/fixtures', class_path)
        m.directory File.join('spec/views', controller_class_path, controller_file_name)

        # Model spec
        m.template('model:fixtures.yml', File.join('spec/fixtures', class_path, "#{table_name}.yml"))
        m.template 'ar_spec_scaffold:model_spec.rb', File.join('spec/models', class_path, "#{file_name}_spec.rb")

        # Controller spec
        m.template 'ar_spec_scaffold:controller_spec.rb',
          File.join('spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb")
        m.template 'ar_spec_scaffold:helper_spec.rb',
          File.join('spec/helpers', class_path, "#{controller_file_name}_helper_spec.rb")

        # View specs
        %w|edit index new show search|.each do |action|
          m.template "ar_spec_scaffold:#{action}_erb_spec.rb",
            File.join('spec/views', controller_class_path, controller_file_name, "#{action}.#{default_file_extension}_spec.rb")
        end
      end

      unless options[:skip_migration]
        m.migration_template(
          'model:migration.rb', 'db/migrate', 
          :assigns => {
            :migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}",
            :attributes     => attributes
          }, 
          :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
        )
      end

      m.route_resources controller_file_name
    end
  end

  protected
    # Override with your own usage banner.
    def banner
      "Usage: #{$0} ar_spec_scaffold ModelName [field:type field:type]"
    end

    def add_options!(opt)
      opt.separator ''
      opt.separator 'Options:'
      opt.on("--skip-migration", 
             "Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
      opt.on("--skip-rspecing", 
             "Don't generate specs") { |v| options[:skip_rspecing] = v }           
    end

    def views_files
      %w|index show new edit search _index_items _search_results|
    end
    
    # inspect template/default_methods files and return a filename relative
    # to the template directory.
    def defaul_methods_files 
      current_dir= File.dirname(File.expand_path(__FILE__))
      files= Dir[File.join(current_dir, 'templates', 'default_methods', '*.rb')]
      files.map {|f| File.join('default_methods', File.basename(f))}
    end

    def model_name 
      class_name.demodulize
    end
end

module Rails
  module Generator
    class GeneratedAttribute
      def default_value
        @default_value ||= case type
          when :int, :integer               then "\"1\""
          when :float                       then "\"1.5\""
          when :decimal                     then "\"9.99\""
          when :datetime, :timestamp, :time then "Time.now"
          when :date                        then "Date.today"
          when :string                      then "\"MyString\""
          when :text                        then "\"MyText\""
          when :boolean                     then "false"
          else
            ""
        end      
      end

      def input_type
        @input_type ||= case type
          when :text                        then "textarea"
          else
            "input"
        end      
      end
    end
  end
end
